package com.donghu.study;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 获取请求中键名为 u 的值
        String username = req.getParameter("u");
        // 获取请求中键名为 p 的值
        String password = req.getParameter("p");
        // 获取请求中键名为 c 的值
        String code = req.getParameter("c");
        System.out.println(username);
        System.out.println(password);
        System.out.println(code);


        HttpSession session = req.getSession();
        Object c = session.getAttribute("C");
        boolean isTrue = c != null && code != null && code.equals(c);
        if (!isTrue){

            resp.sendRedirect("http://localhost:8080/XyY/login.jsp");
//            PrintWriter writer = resp.getWriter();
//            writer.write("code is error");
//            writer.flush();
//            writer.close();
            return;
        }
        String sql="SELECT * FROM `user` WHERE `username`=? AND  `password`=MD5(?)";
        Long id = JdbcUtils.select(sql, Long.class, username, password);
        if (id!=null){
            session.setAttribute("UID",id);
            resp.sendRedirect("http://localhost:8080/XyY/index.jsp");
        }else {
            resp.sendRedirect("http://localhost:8080/XyY/login.jsp");
        }
//        String message = id != null && id>0L? "登录成功！":"登录失败！";
//            //响应结果
//        PrintWriter writer = resp.getWriter();
//        writer.write(message);
//        writer.flush();
//        writer.close();
    }
}


